import axios from 'axios'

//引入nprogress包和css样式
import Nprogress from 'nprogress'
import 'nprogress/nprogress.css'

//引入store实例用来获取userTempId
import store from '@/store'

//创建axios
const service = axios.create({
    baseURL: '/api',
    timeout: 10000
})

//请求拦截器
service.interceptors.request.use(config => {
    // console.log(config)
    Nprogress.start()

    //在请求头中添加userTempId
    let userTempId = store.state.users.userTempId
    if (userTempId) config.headers.userTempId = userTempId

    //在请求头中添加token
    let token = store.state.users.token
    if (token) config.headers.token = token

    return config
}, err => {
    console.log(err);
})

//响应拦截器
service.interceptors.response.use(response => {
    Nprogress.done()
    // console.log(response);

    //返回响应体
    return response.data
}, error => {
    Nprogress.done()
    return Promise.reject(new Error('未知错误......'))
})

export default service
